<?php

namespace app\api\model;
use think\db;
/**
 * 钱包模型
 * Class Category
 * @package app\common\model
 */
class Balance extends BaseModel
{
    protected $table = 'content_balance';

    /**
     * 修改用户资金，添加日志
     *
     * @param $user_id
     * @param $number
     * @param $sign  1加 2减
     * @param $remark
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function changeBalance($user_id,$field,$number,$sign,$from_type,$remark)
    {
        //查询用户之前余额
        $before = $this->where('uid',$user_id)->value($field);
        $balanceLog = new BalanceLog();
        if($sign==2){ //减
            $after = $before-$number;
        }else{//增加
            $after = $before+$number;
        }
        $this->startTrans();
        //修改用户余额
        $decBalance = $this->updateNumber(

            ['uid'=>$user_id],$sign,$field,$number);
        //增加操作日志
        $logRes = $balanceLog->insertInfo([
            'uid'=>$user_id,
            'number'=>$number,
            'sign'=>$sign,
            'before'=>$before,
            'after'=>$after,
            'create_time'=>time(),
            'type' =>$from_type,
            'content' => $remark
        ]);
        if($decBalance && $logRes){
            $this->commit();
            return true;
        }else{
            return false;
            $this->rollback();
        }
    }

    /**
     * 添加用户资金
     */
    public function  addBalance($uid){
        $config=db::name('content_advs_category_config')->find();
        $data=[
          'uid'=>$uid,
          'create_time'=>time(),
          'ontrial_absenteeism'=>$config['success_song'],
        ];
        $isBalance = $this->where('uid',$uid)->find();
        if(!$isBalance){
            $this->startTrans();
            $isok=$this->insert($data);
            if($isok){
                $this->commit();
                return true;
            }else{
                $this->rollback();
                return false;
            }
        }
        return true;
    }
	/**
     * 查询资产
     *
     * @param $user_id
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBalance($user_id)
    {
        $data = $this->getInfo(['uid'=>$user_id]);
        return $data;
    }
}
